"""
@author: Sergiy Tsymbalyuk
"""

from pylons import url
from sqlalchemy import select, func, desc

from catalogue.lib.base import render, Session
from catalogue.model.catalog import Tag, Document, document_tags

from chowa.lib.site.layout import PanelComponent


class TagCloud(object):
    __metaclass__ = PanelComponent
    
    def __init__(self, options={}):
        pass
    
    def render(self):
        query = select([func.count(document_tags.c.document_id).label('docs_count')])
        all_docs = Session.execute(query).first()['docs_count']
        
        query = select([document_tags.c.tag_id,
                        func.count(document_tags.c.document_id).label('docs_count'),
                        Tag.name])
        query = query.where(Tag.id == document_tags.c.tag_id)
        query = query.group_by(document_tags.c.tag_id).order_by(Tag.name)
        tags = []
        for tag in Session.execute(query):
            if tag['docs_count'] > all_docs / 100:
                tag_id = tag['tag_id']
                if len(tag['name']) > 11: tag_caption = tag['name'][:10] + '..'
                else: tag_caption = tag['name']
                tag_url = url(controller='docs', action='tag', id=tag_id)
                tags += [{
                    'caption': tag_caption,
                    'style': 'font-size:%sem;' % (2.5 * tag['docs_count'] / all_docs + 0.7),
                    'url': tag_url,
                    'is_current': tag_url == url.current()
                }]
        return render('/catalogue/tag_cloud.html', extra_vars={'tags': tags})
